package com.hrm.utils;


import java.io.*;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;

public class WordToHtml {
    /**
     * @param inputPath H:/img2/
     * @param fileName  格式：文件名+后缀
     */
    public static void wordToHtml(String inputPath, String fileName, String userId) {

        try {
            // H:/1/abc.txt
            File file = new File(inputPath + fileName);
            //文件夹名
            String folderName = fileName.substring(0, fileName.lastIndexOf("."));
            String str = "";
            if (userId != null && !userId.equals("")) {
                str = "&userId=" + userId;
            }
            String finalStr = str;
            FileInputStream fileInputStream = new FileInputStream(file);
            HWPFDocument wordDocument = new HWPFDocument(fileInputStream);
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());

            wordToHtmlConverter.setPicturesManager(new PicturesManager() {
                private int j = 0;

                public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {

                    // 写入html的图片路径
                    // inputPath + filename(作为文件夹) + / + pict_i + .jpeg
                    return "./getfile?path=" + folderName + "/pict_" + (j++) + ".png" + finalStr;
                }
            });
            wordToHtmlConverter.processDocument(wordDocument);
            // 保存图片
            List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();
            // 保存图片的文件夹
            File folder = new File(inputPath + fileName.substring(0, fileName.lastIndexOf(".")));
            // 不存在则创建
            if (!folder.exists()) {
                folder.mkdirs();
            }
            if (pics != null) {
                for (int i = 0; i < pics.size(); i++) {
                    Picture pic = (Picture) pics.get(i);
                    System.out.println("保存第" + (i + 1) + "张图");
                    try {
                        // 图片保存到本地
                        // inputPath + filename(作为文件夹) + / + pict_i + .jpeg
                        pic.writeImageContent(new FileOutputStream(inputPath + fileName.substring(0, fileName.lastIndexOf(".")) + "/pict_" + i + ".png"));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
            Document htmlDocument = wordToHtmlConverter.getDocument();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            DOMSource domSource = new DOMSource(htmlDocument);
            StreamResult streamResult = new StreamResult(out);

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer serializer = tf.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            serializer.transform(domSource, streamResult);
            out.close();
            String content = new String(out.toByteArray());
            FileUtils.writeStringToFile(new File(inputPath + fileName.substring(0, fileName.lastIndexOf(".")) + ".html"), content, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
